// 用户 登录等
import config from '../request/config'
import {
  showFailToast
} from '../utils/util.js'
import {
  request
} from '../request/index.js'

// 完成登录并获取后台user
export const wxLoginToGetUser = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (res) => {
        if (res.code) {
          getOpenId(res).then((res) => {
            if (res.data.code == 200) {
              var userOpen = {}
              userOpen.openid = res.data.data.openid
              userOpen.session_key = res.data.data.session_key
              wx.setStorageSync('userOpen', userOpen) //存储openid
              getUser({
                qopenid: res.data.data.openid
              }).then((res) => {
                resolve(res)
              })
            }
          })
        } else {
          showFailToast({
            title: '获取用户登录态失败！'
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  })
}

// 微信登录
export const wxLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (res) => {
        resolve(res)
      }
    })
  })
}

// 发送 res.code 到后台换取 openId, sessionKey, unionId
export const getOpenId = (data) => {
  return new Promise((resolve, reject) => {
    var l = config.host + 'getOpenid'
    wx.request({
      url: l,
      data: {
        json: data.code
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        // console.log("getOpenId", res);
        resolve(res)
      }
    })
  })
}

// 获取后台用户
export const getUser = (data = {}) => {
  return request({
    url: 'getQuser',
    data
  })
}

// 更新用户信息
export const upUser = (data = {}) => {
  return request({
    url: 'updateQuser',
    data
  })
}

// 用户信息插入到数据库
export const insertUser = (data = {}) => {
  return request({
    url: 'insertQuser',
    data
  })
}

// 获取 access_token
export const getAccessToken = () => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx74401f78d0c72b6d&secret=5f513792cb432cffb153ad2236b2a2b3', //仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        resolve(res.data)
      },
      fail: (err) => {
        console.log(err)
      }
    })
  })
}

// 获取用户手机号
export const getPhone = (data) => {
  console.log(data)
  if (data.errMsg == 'getPhoneNumber:ok') {
    return request({
      url: 'getPhoneNumber',
      data: {
        encryptedData: data.encryptedData,
        iv: data.iv,
        session_key: wx.getStorageSync('userOpen').session_key
      }
    })
  }
}